﻿using System;

namespace ForgeCraft
{
    public class PickupEntity : Entity
    {
        public InventoryItem Item;

        public int timeInWorld = 0;

        public PickupEntity(int x, int y, int z, InventoryItem item, World world, Velocity vel)
        {
            pos.x = (double)x + .5; pos.y = (double)y; pos.z = (double)z + .5;
            inWorld = world;
            Spawned = true;
            velocity = vel;
            Item = item;
            base.Update();
        }

        override public void Update()
        {
            ChunkBlock cb = inWorld.GetBlock((int)pos.x, (byte)(pos.y - 0.25), (int)pos.z);

            //Logger.Log("EPos: " + (int)pos.x + " " + (byte)(pos.y) + " " + (int)pos.z, LogType.Debug);

            if (cb.type < 1)
            {
                pos.y -= 0.20;
            }

            //base.Update();

            switch ((Block)cb.type)
            {
                case Block.Lava: Despawn(); return;
                case Block.StillLava: Despawn(); return;
                case Block.Portal: Despawn(); return;
            }

            foreach (Player p in Server.playerList)
            {
                if (Math.Abs(p.pos.x - pos.x) < 1 && Math.Abs(p.pos.z - pos.z) < 1 && pos.y <= p.pos.y + 2 && pos.y >= p.pos.y - 0.5)
                {
                    if (p.Inventory.AddItem(Item))
                    {
                        p.PickupCollected(this, p);
                        Despawn();
                        break;
                    }
                }
            }

            this.timeInWorld++;

            // TODO: Add a killspawn config to remove items after x * 5 seconds

            if (this.timeInWorld > 60) Despawn();
        }

        override public void Despawn()
        {
            base.Despawn();
        }

        override public string ToString()
        {
            return "[Entity.Pickup " + id + ": " + Item + "]";
        }
    }
}
